﻿namespace IMServer.Endpoints;

public static class WSEndpoint
{
    public static RouteGroupBuilder MapWSEndpoint(this RouteGroupBuilder group)
    {
        // WebSocket连接处理
        group.Map("", async (HttpContext context) =>
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                context.Response.StatusCode = 400;
                return;
            }

            // 从请求头或query参数中获取用户ID
            var userId = context.Request.Query["UserId"].ToString();
            if (string.IsNullOrEmpty(userId))
            {
                context.Response.StatusCode = 401;
                return;
            }

            try
            {
                await WebSocketManager.Instance.HandleConnectionAsync(context, userId);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"WebSocket error: {ex.Message}");
            }
        });

        return group;
    }
}